<?php

class ErrorHandler {
	private static $shutdown;
	public static function handleException(Exception $exception) {
		self::shutdown("Exception " . $exception->getMessage(), $exception->getFile(), $exception->getLine(), $exception->getTrace());
	}

	public static function handleError($errno, $msg, $file, $line) {
		if ($errno) {
			throw new ErrorException($msg, 0, $errno, $file, $line);
		}
		//self::shutdown($msg, $file, $line, array_slice(debug_backtrace(), 0, -1));
	}

	public static function handleShutdown() {
		if ( ($err = error_get_last()) !== NULL) {
			self::shutdown(
				$err['message'],
				$err['file'],
				$err['line'],
				array_slice(debug_backtrace(), 0, -1)
			);
		}
	}

	private static function _exit() {
		Storage::closeConnections();
		exit();
	}

	private static function shutdown($msg, $file, $line, $backtrace) {
		if (self::$shutdown) self::_exit();
		self::$shutdown = true;

		if (ON_PRODUCTION) {
			if (isset($_GET['error'])) {
				echo backtrace_html($backtrace) . debug_info_html("$msg in $file on $line");
			} else {
				Email::report('【教务管理系统】线上错误', backtrace_html($backtrace) . debug_info_html("$msg in $file on $line"));
			}
		} else {
			echo backtrace_html($backtrace) . debug_info_html("$msg in $file on $line");
		}

		$data = array('body' => '发生了一个内部错误，已经自动通知了工程师，请稍后再次访问!', 'state' => '500');
		if (!ON_PRODUCTION) {
			$data['body'] = "\n{$msg}\n{$file} line:{$line}\n";
		}
		echo new View('message', $data);
		self::_exit();
	}

	public static function backtraceHtml(Exception $exception) {
		return backtrace_html($exception->getTrace());
	}
}